import axios, { AxiosRequestConfig, AxiosInstance } from 'axios';
import store from '@/store';

function errorText(statusCode: number) {
	switch (statusCode) {
		case 404:
			console.log('不存在此数据接口');
			break;
		default:
			console.log('未知错误');
	}
}

export default class Request {
	static posUrl(url: string): boolean {
		/* 判断url是否为绝对路径 */
		return /(http|https):\/\/([\w.]+\/?)\S*/.test(url);
	}

	request<T>(options: AxiosRequestConfig) {
		const instance = axios.create({
			baseURL: 'http://121.43.128.139:7086'
		});

		// 添加请求拦截器
		instance.interceptors.request.use(
			function(config) {
				// 在发送请求之前做些什么
				const token = localStorage.getItem('token');
				console.log('---------request---------');
				console.log(token);
				console.log('---------request---------');

				if (token) {
					config.headers['Authorization'] = `Bearer ${token}`;
					config.headers['Accept'] = 'application/json';
					// config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
					// store.dispatch('logined', localStorage.token)
				}
				return config;
			},
			function(error) {
				// 对请求错误做些什么
				return Promise.reject(error);
			}
		);

		// 添加响应拦截器
		instance.interceptors.response.use(
			function(response) {
				// 对响应数据做点什么
				console.dir(`response ${response}`);
				return response.data;
			},
			function(error) {
				// 对响应错误做点什么
				console.dir(error);
				console.dir(error.response.status);
				return Promise.reject(error);
			}
		);

		return instance.request<T>({
			...options
		});
	}

	get<T = any>(url: string, options: AxiosRequestConfig = {}) {
		return this.request<T>({
			url,
			method: 'get',
			...options
		});
	}

	post<T = any>(url: string, data?: any, options: AxiosRequestConfig = {}) {
		return this.request<T>({
			url,
			data,
			method: 'post',
			...options
		});
	}

	put<T = any>(url: string, data?: any, options: AxiosRequestConfig = {}) {
		return this.request<T>({
			url,
			data,
			method: 'put',
			...options
		});
	}

	delete<T = any>(url: string, data: object = {}, options: AxiosRequestConfig = {}) {
		return this.request<T>({
			url,
			data,
			method: 'DELETE',
			...options
		});
	}
}
